<template>
    <div class="sys-role-container flex flex-col">
        <a-card class="mb-2.5">
            <common-form
                :model="state.queryForm"
                name="menu-form"
                @query="handleQuery"
                @add="handleAdd"
                @reset="handleReset"
            >
                <a-form-item
                    v-if="userInfoStore.state.userInfos.accountType == 999"
                    label="租户"
                    name="tenantId"
                    style="width: 250px;"
                >
                    <a-select v-model:value="state.queryForm.tenantId" placeholder="">
                        <a-select-option
                            v-for="item in state.tenantList"
                            :key="item.value"
                            :value="item.value">
                            {{item.label}}    
                        </a-select-option>
                    </a-select>
                </a-form-item>
                <a-form-item
                    label="角色名称"
                    name="name"
                    class="w-1/2.5"
                >
                    <a-input v-model:value="state.queryForm.name"/>
                </a-form-item>
                <a-form-item
                    label="角色编码"
                    name="code"
                    class="w-1/2.5"
                >
                    <a-input v-model:value="state.queryForm.code"/>
                </a-form-item>
            </common-form>
        </a-card>
        <a-card class="flex-1 card-table">
            <common-table 
                :columns="columns" 
                :data="state.tableData"
                :pagination="{
                        total: state.tableParams.total,
                        current: state.tableParams.page,
                        pageSize: state.tableParams.pageSize,
                        showQuickJumper: true,
                        showSizeChanger: true,
                        pageSizeOptions:['2','5','10','20'],
                        showTotal:(total:number) => `总数: ${total}`
                }"
                :loading="state.loading"
                @change="changePagination"
            >
                <template #bodyCell="{ column, text, record }">
                    <template v-if="column.dataIndex === 'dataScope'">
                        <a-tag color="cyan">
                            <template v-for="item in useMapDictList('DataScopeEnum')" :key="item.value">
                                <template v-if="record.dataScope == 1 && record.dataScope == item.value">{{ item.label }}</template>
                                <template v-if="record.dataScope == 2 && record.dataScope == item.value">{{ item.label }}</template>
                                <template v-if="record.dataScope == 3 && record.dataScope == item.value">{{ item.label }}</template>
                                <template v-if="record.dataScope == 4 && record.dataScope == item.value">{{ item.label }}</template>
                                <template v-if="record.dataScope == 5 && record.dataScope == item.value">{{ item.label }}</template>
                            </template>
                        </a-tag>
                    </template>
                    <template v-if="column.dataIndex === 'status'">
                        <a-switch v-model:checked="record.status" :checkedValue="1" @change="handleStausChange(record)"/>
                    </template>
                    <template v-if="column.dataIndex ==='history'">
                        <div style="cursor: pointer;">
                            <edit-record-history :row="record"/>
                        </div>
                    </template>
                    <template v-if="column.dataIndex === 'operation'">
                        <div class="w-full">
                            <a-button :icon="h(BarChartOutlined)" ghost type="primary" class="mr-1"@click=handleOpen(record) v-auth="'sysRole:update'">数据范围</a-button>
                            <a-popconfirm
                                title="确定删除?"
                                @confirm="handleDelete(record)"
                            >
                                <a-button v-auth="'sysRole:delete'" :icon="h(DeleteOutlined)" danger >删除</a-button>
                            </a-popconfirm>
                        </div>
                    </template>
                    <template v-if="column.dataIndex === 'operationauth'">
                        <div class="w-full">
                            <a-button :icon="h(EditOutlined)" ghost type="primary" class="mr-1" @click="handleEdit(record)" v-auth="'sysRole:update'">编辑菜单</a-button>
                            <a-button :icon="h(EditOutlined)" ghost type="primary" class="mr-1" @click="handleEditBtn(record)" v-auth="'sysRole:update'">编辑按钮</a-button>
                        </div>
                    </template>
                </template>
            </common-table>
        </a-card>
        <data-scope-modal ref="dataScopeModalRef"@handle-query="handleQuery"/>
        <edit-role ref="editRoleRef" @handle-query="handleQuery"/>
        <edit-button-auth ref="editButtonAuthRef" @handle-query="handleQuery"/>
    </div>
</template>

<script setup lang="ts" name="sysRole">
import { onMounted,reactive,h,ref, useTemplateRef } from 'vue';
import { apiSysRoleDeletePost, apiSysRolePagePost, apiSysRoleSetStatusPost } from '@/api/sys/sysRole';
// @ts-ignore
import { Splitpanes, Pane } from 'splitpanes'
import orgTree from "../org/components/orgTree.vue";
import CommonForm from '@/components/common-form/index.vue'
import CommonTable from '@/components/common-table/index.vue'
import { useUserInfo } from '@/stores/userInfo';
import { apiSysTenantListGet } from '@/api/sys/sysTenant';
import type { ResType } from '@/api/types';
import type { TableParamsResType, TenantListType } from '../onlineUser/type';
import type { ItemType } from './type';
import editRecordHistory from "@/components/self/edit-record-history.vue";
import {EditOutlined,DeleteOutlined,BarChartOutlined} from '@ant-design/icons-vue'
import dataScopeModal from './components/dataScopeModal.vue';
import { useMapDictList } from '@/hooks';
import editRole from './components/editRole.vue';
import { emitter, showMsg } from '@/utils';
import editButtonAuth from './components/editButtonAuth.vue';

defineOptions({
    name: "sysRole",
})

const editButtonAuthRef = useTemplateRef("editButtonAuthRef")
const editRoleRef = ref<InstanceType<typeof editRole>>()
const userInfoStore = useUserInfo()
const dataScopeModalRef = ref<InstanceType <typeof dataScopeModal>>()
const state = reactive({
    queryForm:{
		tenantId: undefined,
		name: undefined,
		code: undefined,
    } as any,
    tableData:[] as ItemType[],
    loading:false,
    tenantList:[] as TenantListType,
    tableParams: {
		page: 1,
		pageSize: 50,
		total: 0 as any,
	},
})
const columns:any[] = [
    {
        title: '序号',
        align: "center",
        width: 60,
        customRender: ({ index }:{index:number}) => {
            return `${ index + 1 }`;
        },
        fixed: 'left',
    },
    {
        title: '角色名称',
        dataIndex: 'name',
        key: 'name',
        align: 'center',
        width: 150,
    },  
    {
        title: '角色编码',
        dataIndex: 'code',
        key: 'code',
        align: 'center',
        width: 150,
    },  
    {
        title: '数据范围',
        dataIndex: 'dataScope',
        key: 'dataScope',
        align: 'center',
        width: 150,
    }, 
    {
        title: '排序',
        dataIndex: 'orderNo',
        key: 'orderNo',
        align: 'center',
        width: 150,
    }, 
    {
        title: '状态',
        dataIndex: 'status',
        key: 'status',
        align: 'center',
        width: 150,
    }, 
    {
        title: '修改记录',
        dataIndex: 'history',
        key: 'history',
        align: 'center',
        width: 150,
    }, 
    {
        title: '操作',
        align: 'center',
        key:"operation",
        dataIndex: 'operation',
        width: 250,
        fixed: 'right',
    },
    {
        title: '权限操作',
        align: 'center',
        key:"operationauth",
        dataIndex: 'operationauth',
        width: 250,
        fixed: 'right',
    }
]

const handleAdd = ()=>{
    editRoleRef.value?.handleOpen({ id: undefined, status: 1, tenantId: state.queryForm.tenantId, orderNo: 100 })
}
const handleEdit = (record:ItemType)=>{
    editRoleRef.value?.handleOpen(record)
}
const handleEditBtn = (record?:ItemType)=>{
    editButtonAuthRef.value?.handleOpen(record)
}
const handleReset =async ()=>{
    state.queryForm = {
        tenantId: undefined,
        name: undefined,
        code: undefined,
    }
    state.queryForm.tenantId = state.tenantList[0].value;
    await handleQuery()
}

const handleDelete = async(record:ItemType)=>{
    await apiSysRoleDeletePost({ id: record.id })
    showMsg("删除成功","success")
    await handleQuery()
}

const handleQuery = async()=>{
    state.loading = true
    let params = Object.assign(state.queryForm,state.tableParams)
    let res = await apiSysRolePagePost({...params}) as ResType<TableParamsResType<ItemType>>
    state.tableData = res.data.result.items ?? []
    state.tableParams.total = res.data.result.total ?? 0
    state.loading = false
}
const changePagination = async(pagination:{current:number,pageSize:number})=>{
    state.tableParams.page = pagination.current
    state.tableParams.pageSize = pagination.pageSize
    await handleQuery()
}

const handleOpen = (record:ItemType)=>{
    dataScopeModalRef.value?.handleOpen(record)
}

const handleStausChange = async (row:ItemType)=>{
    await apiSysRoleSetStatusPost({ id: row.id, status: row.status ? 1 : 2 })
    showMsg('操作成功','success')
    await handleQuery()
    emitter.emit('posOrRoleUpdate')
}

onMounted(async()=>{
    if (userInfoStore.state.userInfos.accountType === 999) {
        const res = await apiSysTenantListGet() as ResType<TenantListType>;
        state.tenantList = res.data.result;
        state.queryForm.tenantId = state.tenantList[0].value;
    }
    await handleQuery()

    emitter.on("update-role-btn-auth",(record:any)=>{
        editButtonAuthRef.value?.handleOpen(record)
    })
})
</script>

<style lang="scss" scoped>
.sys-role-container{
    .card-table{
        :deep(.ant-card-body){
            height: 100%;
        }
    }
}
:deep(.ant-table-cell-fix-right){
    // right: 0 !important;
}
:deep(.ant-btn >span) {
    display:inline-flex!important;
}
</style>
